<template>
  <div class="list-container">
    <div class="add-btn" v-if="currentUser.username">
      <button @click="createQuestionnaire">新建问卷</button>
    </div>

    <div class="questionnaire-list">
      <div v-for="item in questionnaireList" :key="item.id" class="questionnaire-item">
        <div class="questionnaire-info">
          <h3>{{ item.title }}</h3>
          <div class="meta-info">
            <span>创建者：{{ getCreatorName(item) }}</span>
            <span>状态：{{ item.stateName }}</span>
            <span>创建时间：{{ formatDate(item.time) }}</span>
            <span v-if="item.deadline">截止时间：{{ formatDate(item.deadline) }}</span>
          </div>
        </div>
        <div class="operations">
          <template v-if="!isAdmin && item.creator !== currentUser.username">
            <button v-if="item.state === 1" @click="fillQuestionnaire(item.id)">填写问卷</button>
            <span v-else-if="item.state === 0">未发布</span>
            <span v-else>已结束</span>
          </template>
          
          <template v-else>
            <button v-if="item.state !== 2" @click="editQuestionnaire(item.id)">编辑问卷</button>
            <button v-if="item.state === 0" @click="publishQuestionnaire(item.id)">发布问卷</button>
            <button v-if="item.state === 1" @click="fillQuestionnaire(item.id)">填写问卷</button>
            <button v-if="item.state !== 0" @click="viewData(item.id)">查看数据</button>
            <button v-if="item.state === 1" @click="endQuestionnaire(item.id)">结束问卷</button>
            <button v-if="item.state === 2" @click="restartQuestionnaire(item.id)">重新开始</button>
            <button @click="deleteQuestionnaire(item.id)">删除问卷</button>
          </template>
        </div>
      </div>
    </div>

    <div class="modal" v-if="showPublishModal">
      <div class="modal-content">
        <h3>设置问卷截止时间</h3>
        <div class="input-group">
          <label>截止时间：</label>
          <input 
            type="datetime-local" 
            v-model="deadlineTime"
            :min="minDateTime"
            step="60"
          >
        </div>
        <div class="modal-buttons">
          <button @click="confirmPublish" class="confirm">确认发布</button>
          <button @click="showPublishModal = false" class="cancel">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ListComponent',
  data() {
    return {
      questionnaireList: [],
      isAdmin: false,
      showPublishModal: false,
      deadlineTime: '',
      currentQuestionnaireId: null,
      currentUser: JSON.parse(localStorage.getItem('currentUser') || '{}')
    }
  },
  computed: {
    minDateTime() {
      const now = new Date()
      return now.toISOString().slice(0, 16)
    }
  },
  created() {
    this.loadUserRole()
    this.loadQuestionnaires()
  },
  methods: {
    loadUserRole() {
      const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}')
      this.isAdmin = currentUser.isAdmin || false
    },
    loadQuestionnaires() {
      this.questionnaireList = JSON.parse(localStorage.getItem('questionnaire') || '[]')
      
      if (!this.isAdmin) {
        this.questionnaireList = this.questionnaireList.filter(item => 
          item.state === 1 || item.creator === this.currentUser.username
        )
      }
    },
    createQuestionnaire() {
      this.$router.push('/edit/0')
    },
    editQuestionnaire(id) {
      this.$router.push(`/edit/${id}`)
    },
    fillQuestionnaire(id) {
      this.$router.push(`/fill/${id}`)
    },
    viewData(id) {
      this.$router.push(`/data/${id}`)
    },
    publishQuestionnaire(id) {
      this.currentQuestionnaireId = id
      this.deadlineTime = ''
      this.showPublishModal = true
    },
    confirmPublish() {
      if (!this.deadlineTime) {
        alert('请设置截止时间')
        return
      }

      const deadlineDate = new Date(this.deadlineTime)
      const now = new Date()

      if (deadlineDate <= now) {
        alert('截止时间必须大于当前时间')
        return
      }

      const questionnaire = this.questionnaireList.find(q => q.id === this.currentQuestionnaireId)
      if (questionnaire) {
        questionnaire.state = 1
        questionnaire.stateName = '发布中'
        questionnaire.deadline = deadlineDate.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
        questionnaire.publishTime = now.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
        localStorage.setItem('questionnaire', JSON.stringify(this.questionnaireList))
      }

      this.showPublishModal = false
      this.startDeadlineCheck()
    },
    endQuestionnaire(id) {
      if (confirm('确定要结束这个问卷吗？结束后可以重新开始。')) {
        const questionnaire = this.questionnaireList.find(q => q.id === id)
        if (questionnaire) {
          questionnaire.state = 2
          questionnaire.stateName = '已结束'
          questionnaire.endTime = new Date().toISOString()
          localStorage.setItem('questionnaire', JSON.stringify(this.questionnaireList))
        }
      }
    },
    restartQuestionnaire(id) {
      this.currentQuestionnaireId = id
      this.deadlineTime = ''
      this.showPublishModal = true
    },
    deleteQuestionnaire(id) {
      const index = this.questionnaireList.findIndex(q => q.id === id)
      if (index !== -1) {
        this.questionnaireList.splice(index, 1)
        localStorage.setItem('questionnaire', JSON.stringify(this.questionnaireList))
      }
    },
    startDeadlineCheck() {
      setInterval(() => {
        const now = new Date()
        let needUpdate = false

        this.questionnaireList.forEach(q => {
          if (q.state === 1 && q.deadline) {
            const deadlineDate = new Date(q.deadline)
            if (now >= deadlineDate) {
              q.state = 2
              q.stateName = '已结束'
              q.endTime = now.toISOString()
              needUpdate = true
            }
          }
        })

        if (needUpdate) {
          localStorage.setItem('questionnaire', JSON.stringify(this.questionnaireList))
          this.loadQuestionnaires()
        }
      }, 60000)
    },
    getCreatorName(questionnaire) {
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const creator = users.find(user => user.username === questionnaire.creator)
      return creator?.nickname || questionnaire.creator || '未知用户'
    },
    formatDate(dateString) {
      if (!dateString) return '未设置'
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return '无效日期'
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (e) {
        return '无效日期'
      }
    }
  },
  mounted() {
    this.startDeadlineCheck()
  }
}
</script>

<style lang="scss" scoped>
.list-container {
  padding: 20px;

  .add-btn {
    margin-bottom: 20px;
    
    button {
      padding: 10px 20px;
      background: #ee7419;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background: #d65f0a;
      }
    }
  }

  .questionnaire-item {
    background: white;
    padding: 15px 20px;
    margin-bottom: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20px;

    .questionnaire-info {
      flex: 1;
      min-width: 0;

      h3 {
        font-size: 16px;
        color: #333;
        margin-bottom: 8px;
      }

      .meta-info {
        font-size: 14px;
        color: #666;

        span {
          margin-right: 20px;
          
          &:last-child {
            margin-right: 0;
          }
        }
      }
    }

    .operations {
      flex: 0 0 auto;
      display: flex;
      gap: 8px;
      margin-left: auto;
      min-width: 400px;
      justify-content: flex-end;

      button {
        padding: 6px 12px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        background: #ee7419;
        color: white;

        &:hover {
          background: #d65f0a;
        }

        &:nth-child(1) { background: #1890ff; }
        &:nth-child(2) { background: #52c41a; }
        &:nth-child(3) { background: #722ed1; }
        &:nth-child(4) { background: #faad14; }
        &:nth-child(5) { background: #ff4d4f; }
        &:nth-child(6) { background: #13c2c2; }
        &:last-child { background: #ff4d4f; }

        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .modal-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    width: 400px;

    h3 {
      margin-bottom: 20px;
      color: #333;
    }

    .input-group {
      margin-bottom: 20px;

      label {
        display: block;
        margin-bottom: 8px;
        color: #666;
      }

      input {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;

        &:focus {
          outline: none;
          border-color: #ee7419;
        }
      }
    }

    .modal-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;

      button {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;

        &.confirm {
          background: #ee7419;
          color: white;
          &:hover { background: #d65f0a; }
        }

        &.cancel {
          background: #f5f5f5;
          color: #666;
          &:hover { background: #e8e8e8; }
        }
      }
    }
  }
}
</style>
